<template>
	<view class="address-manage rf-row-wrapper">	
		<view class="row b-b">
			<text class="tit">家人名*</text>
			<input
				class="input"
				type="text"
				v-model="addressData.customName"
				@blur="handlecustomNameChange"
				:placeholder="manageType === 'add' ? '输入家人姓名或扫描老人二维码' : '输入家人姓名'"
				placeholder-class="placeholder"
			/>
			<text v-if="manageType === 'add' " class="cell-more iconfont iconsaomiao" @tap.stop="handleSaoMiao"></text>
		</view>
		<view class="row b-b">
			<text class="tit">手机号</text>
			<input
				class="input"
				type="number"
				v-model="addressData.homeTel"
				@blur="handleMobileChange"
				placeholder="家人手机号"
				placeholder-class="placeholder"
			/>
		</view>
		<view class="row b-b">
			<text class="tit">身份证*</text>
			<!--地址三级联动-->
<!-- 			<rf-pick-regions
				:addressData="addressData"
				@getRegions="handleGetRegions"
			>
			</rf-pick-regions> -->
			<input
				class="input"
				type="idcard"
				v-model="addressData.idCard"
				@blur="handleIdCardChange"
				placeholder="家人身份证号"
				placeholder-class="placeholder"
			/>			
		</view>
		<view class="row b-b">
			<text class="tit">家人关系</text>
			<input
				class="input"
				type="text"
				v-model="addressData.memo"
				@blur="bindAddressDetailsChange"
				placeholder="请输入家人关系"
				placeholder-class="placeholder"
			/>
		</view>
		<view class="row default-row" v-if="manageType === 'edit' ? true : false ">
			<text class="tit">设为默认</text>
			<switch
				:checked="addressData.id === defaultCstmId ? true : false"
				:color="themeColor.color"
				@change="switchChange"
			/>
		</view>
		<button
			class="add-btn"
			:class="'bg-' + themeColor.name"
			:disabled="btnLoading"
			:loading="btnLoading"
			@tap="confirm"
		>
			{{this.manageType === 'edit' ? '取消关联' : '提交申请'}}
		</button>

		<!--加载动画-->
		<rfLoading isFullScreen :active="loading"></rfLoading>
	</view>
</template>

<script>
/**
 * @des 家人列表
 *
 * @author stav stavyan@qq.com
 * @date 2020-03-10 18:00
 * @copyright 2019
 */
import { cstmBind, addressUpdate, cstmDetail,decryptQRCode,cstmDelete,scanBind } from '@/api/userInfo';
import rfPickRegions from '@/components/rf-pick-regions';
import rfSearchBar from '@/components/rf-search-bar';
export default {
	components: {
		rfPickRegions,
		rfSearchBar
	},
	data() {
		return {
			addressData: {},
			btnLoading: false,
			multiArray: [[], [], []],
			multiIndex: [0, 0, 0],
			loading: true,
			userInfo : {},
			manageType : '',
			cstmId : 0,
			defaultCstmId : 0,
		};
	},
	onLoad(options) {
		this.initData(options);
	},
	methods: {
		//扫一扫
		handleSaoMiao(){
			const _this = this;
			/*  #ifndef H5  */
			uni.scanCode({
				success: function (res) {
					/*
					_this.$http.get(`${saveWatch}`, this.cstmData).then(() => {
						if(r.data.success){
						  _this.$mHelper.toast('绑定成功');
						}else{
							_this.$mHelper.toast(`绑定失败${r.data.msg}`);
						}

					}).catch(err => {
						_this.$mHelper.toast(err);
					});*/
					//this.cstmData.imieCode = res.result;
					_this.handleQR(res.result);
				},
				fail(res) {
					// 支付成功后的回调函数
					_this.$mHelper.toast('扫描失败：' + res.errMsg);
				}
			});
			/*  #endif  */
			/*  #ifdef H5  */
			if (this.$mPayment.isWechat()) {
				jweixin.ready(() => {
					jweixin.scanQRCode({
						needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
						success(res) {
							/*
							_this.$http.get(saveWatch, this.cstmData).then(() => {
								if(r.data.success){
								  _this.$mHelper.toast('绑定成功');
								}else{
									_this.$mHelper.toast(`绑定失败${r.data.msg}`);
								}
							});*/
							_this.handleQR(res.result);					
							
						},
						fail(res) {
							// 支付成功后的回调函数
							_this.$mHelper.toast('扫描失败：' + res.errMsg);
						}
					});
				});
			} else {
				this.$mHelper.toast('请在微信H5进行相关操作');
			}
			/*  #endif  */				
			},	
	   async handleQR(content){			 
			let params =  {
						qcode :content,
					}
		    let that = this;			
			await this.$http
				.get(`${decryptQRCode}`, params)
				.then(async r => {
					this.loading = false;
					if(r.data && r.data.obj){
						let arr = [];
						arr = r.data.obj.split(',');
						let cstmId = arr[0];
						let cstmType = arr[2];
						let msg = '姓名：'+arr[1];                             
						uni.showModal({
							title: '申请关联老人',
							content: msg,
							success: function (res) {
								if (res.confirm) {
									//console.log('用户点击确定');
									that.linkCstm(cstmId,cstmType)
								} else if (res.cancel) {
									//console.log('用户点击取消');
								}
							}
						});
						
					}
				})
				.catch(() => {
					this.loading = false;
				});			
		},				
		// 获取选择的地区
		handleGetRegions(e) {
			this.addressData.province_id = e.province_id;
			this.addressData.city_id = e.city_id;
			this.addressData.area_id = e.area_id;
		},
		// 数据初始化
		async initData(options) {
			this.userInfo = uni.getStorageSync('userInfo');		
			this.cstmId = options.id;
			this.defaultCstmId = uni.getStorageSync('defaultCstmId');
			let title = '新增家人';
			if (options.type === 'edit') {
				title = '老人信息';
				await this.getAddressDetail(options.id);
			} else {
				setTimeout(() => {
					this.loading = false;
				}, 1 * 1000);
			}
			this.manageType = options.type;
			console.log("this.manageType: " + this.manageType);
			uni.setNavigationBarTitle({
				title
			});
		},
		// 获取家人
		async getAddressDetail(id) {
			let params =  {
						userId :this.userInfo && this.userInfo.userId,
						corpId : this.userInfo && this.userInfo.corpId,
						cstmId : id
					}
			await this.$http
				.get(`${cstmDetail}`, params)
				.then(async r => {
					this.addressData = await r.data;
					this.loading = false;
				})
				.catch(() => {
					this.loading = false;
				});
		},
		handlecustomNameChange(e) {
			this.addressData.customName = e.detail.value;
		},
		bindAddressDetailsChange(e) {
			this.addressData.memo = e.detail.value;
		},
		handleMobileChange(e) {
			this.addressData.homeTel = e.detail.value;
		},
		handleIdCardChange(e) {
			this.addressData.idCard = e.detail.value;
		},		
		switchChange(e) {
			if (e.detail.value) {
				uni.setStorageSync("defaultCstmId", this.addressData.id);
				uni.setStorageSync("defaultCstmName", this.addressData.customName);
				uni.setStorageSync("defaultCstmTel", this.addressData.homeTel);
				uni.setStorageSync("defaultCstmAddr", this.addressData.homeAddress);
			} else {
				uni.setStorageSync("defaultCstmId", 0);
				uni.setStorageSync("defaultCstmName", '');
			}			
			
		},
		// 提交
		confirm() {
			let data = this.addressData;
			if (!data.customName) {
				this.$mHelper.toast('请填写家人姓名');
				return;
			}
			if (!data.idCard) {
				this.$mHelper.toast('请填写家人身份证号');
				return;
			}			
			/*
			if (!/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(data.homeTel)) {
				this.$mHelper.toast('请输入正确的手机号码');
				return;
			}*/
			this.btnLoading = true;
			if (this.manageType === 'edit') {
				this.handleAddressUpdate(data);
				
			} else {
				this.handleAddressCreate(data);
			}
		},
		async handleAddressUpdate(data) {
			await this.$http
				.get(`${cstmDelete}`, {
						userId : this.userInfo && this.userInfo.userId,
						userType : this.userInfo && this.userInfo.userType,
						cstmId : data.id
				})
				.then(r => {
					if(r.data.success){
						this.btnLoading = false;
						this.$mHelper.toast('家人修改成功！');
						this.$mRouter.back();
					}else{
						this.$mHelper.toast(r.data.msg);
					}
				})
				.catch(() => {
					this.btnLoading = false;
				});
		},
		async handleAddressCreate(data) {
			let params = {
            userId: this.userInfo && this.userInfo.userId,
            userType: this.userInfo && this.userInfo.userType,
            corpId:this.userInfo && this.userInfo.corpId,
            cName:data.customName,
            cId:data.idCard,
            cMemo:data.memo
          
          }
			await this.$http
				.get(`${cstmBind}`, params)
				.then(r => {
					console.log("申请返回: " + JSON.stringify(r.data));
					if(r.data.success){
						this.btnLoading = false;
						this.$mHelper.toast('家人绑定申请已提交，等待审核!');
						this.$mRouter.back();						
					}else{
						this.btnLoading = false;
						this.$mHelper.toast(r.data.msg);						
						
					}

				})
				.catch(() => {
					this.btnLoading = false;
				});
		},
		async linkCstm(cstmId,codeType) {
			let params = {
            userId: this.userInfo && this.userInfo.userId,
            userType: this.userInfo && this.userInfo.userType,
            corpId:this.userInfo && this.userInfo.corpId,
            codeId:cstmId,
            codeType:codeType          
          }
			await this.$http
				.get(`${scanBind}`, params)
				.then(r => {
					if(r.data.success){
						this.btnLoading = false;
						this.$mHelper.toast('家人绑定申请已提交，等待审核!');
						this.$mRouter.back();						
					}else{
						this.btnLoading = false;
						this.$mHelper.toast(r.data.msg);						
						
					}

				})
				.catch(() => {
					this.btnLoading = false;
				});
		}		
	}
};
</script>

<style lang="scss">
page {
	background: $page-color-base;
}
.address-manage {
	padding-top: 16upx;
}
</style>
